var prefix = jsctx + "/elecStation";

var elecStationPrice = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/exportPrice", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                elecStationId: $("#elecStationId").val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listElecStationPrice",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20],
                    pageNumber: 1,
                    sidePagination: "server",
                    cache: false,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            elecStationId: $("#elecStationId").val().trim()
                        }
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'stationName', title: '站点名称', width: '100', align: 'right'},
                        {
                            field: 'priceCode', title: '时段', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '1') {
                                    return '<span>尖峰</span>'
                                } else if (value == '2') {
                                    return '<span >高峰</span>'
                                } else if (value == '3') {
                                    return '<span>平段</span>'
                                } else if (value == '4') {
                                    return '<span>低谷</span>'
                                }
                            }
                        },
                        {field: 'elecPrice', title: '基本电费单价(元)', width: '100', align: 'right'},
                        {field: 'servicePrice', title: '服务费单价(元)', width: '100', align: 'right'},
                        {field: 'beginDate', title: '开始日期', width: '100', align: 'left'},
                        {field: 'endDate', title: '结束日期', width: '100', align: 'left'},
                        {field: 'beginTime', title: '开始时间', width: '100', align: 'left'},
                        {field: 'endTime', title: '结束时间', width: '100', align: 'left'},
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="编辑" onclick="elecStationPrice.editElecStationPrice(\''
                                    + row.priceId
                                    + '\')">编辑</a> ';

                                var b = '<a class="btn btn-warning btn-sm ' + has_edit + '" href="#" title="删除" onclick="elecStationPrice.deleteElecStationPrice(\''
                                    + row.priceId
                                    + '\')">删除</a> ';

                                return a + b;
                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function addElecStationPrice(elecStationId) {
        location.href = prefix + "/addElecStationPrice/" + elecStationId;
    }

    function editElecStationPrice(priceId) {
        location.href = prefix + "/editElecStationPrice/" + priceId;
    }

    function elecStationPriceListPage(elecStationPriceId) {
        location.href = prefix + "/elecStationPriceListPage/" + elecStationPriceId;
    }

    function deleteElecStationPrice(priceId) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/deleteElecStationPrice",
                type: "post",
                data: {
                    'priceId': priceId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function goBack() {
        window.history.back();
    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        addElecStationPrice: addElecStationPrice,
        elecStationPriceListPage: elecStationPriceListPage,
        deleteElecStationPrice: deleteElecStationPrice,
        exportList: exportList,
        editElecStationPrice: editElecStationPrice
    };
})();

var addElecStationPrice = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateElecStationPrice",
                data: $('#addElecStationPrice').serialize(),
                async: false,
                error: function (request) {
                    isajaxsend = true
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        // synchronizeHlhtStationPrice();
                        isajaxsend = false
                        parent.layer.msg("操作成功");
                        elecStationPrice.goBack();
                    } else {
                        isajaxsend = true
                        parent.layer.alert(data.message)
                    }

                }
            });
        }
    }

    function synchronizeHlhtStationPrice() {
        $.ajax({
            cache: true,
            type: "POST",
            url: jsctx + "/hlhtTenantOpenList/synchronizeHlhtStationPrice",
            data: {},
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                } else {
                    parent.layer.alert(data.message)
                }

            },
            complete: function () {
                isajaxsend = false
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#addElecStationPrice").validate({
            rules: {
                elecPrice: {
                    required: true,
                    number: true,
                    min: 0,
                },
                servicePrice: {
                    required: true,
                    number: true,
                    min: 0,
                },
                beginTime: {
                    required: true
                },
                endTime: {
                    required: true
                }
            },
            messages: {
                elecPrice: {
                    required: icon + "请输入基本电费单价",
                    number: icon + "基本电费价格式不正确，请输入正确格式",
                    min: icon + "基本电费价不能为负数"
                },
                servicePrice: {
                    required: icon + "请输入基本电费单价",
                    number: icon + "基本电费价格式不正确，请输入正确格式",
                    min: icon + "基本电费价不能为负数"
                },
                beginTime: {
                    required: icon + "请选择开始时间"
                },
                endTime: {
                    required: icon + "请选择结束时间"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();
